package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.pojo.SpecGroupDTO;
import com.leyou.item.pojo.SpecParamDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupService {
    @Autowired
    SpecGroupMapper specGroupMapper;
    @Autowired
    SpecParamService specParamService;
    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);
        List<SpecGroup> specGroupList = specGroupMapper.select(specGroup);
        if(CollectionUtils.isEmpty(specGroupList)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        List<SpecGroupDTO> specGroupDTOS = BeanHelper.copyWithCollection(specGroupList, SpecGroupDTO.class);
        return specGroupDTOS;
    }
    //根据分类id查询规格组和所携带的规格参数
    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        //查询该分类的规格组
        List<SpecGroupDTO> specGroupDTOS = queryGroupByCategory(id);
        //查询该分类的全部规格参数
        List<SpecParamDTO> specParamDTOS = specParamService.querySpecParams(null, id, null);
        Map<Long, List<SpecParamDTO>> paramMap = specParamDTOS
                .stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));//根据groupid分类
        //二者对应起来
        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            specGroupDTO.setParams(paramMap.get(specGroupDTO.getId()));
        }
        return specGroupDTOS;
    }
}
